package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.SAttribute;
import com.example.mapper.SAttributeMapper;
import com.example.service.SAttributeService;
import com.example.vo.AttributeVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * <p>
 * 商品属性可选项 服务实现类
 * </p>
 *
 * @author zh
 * @since 2024-05-13 10:37:00
 */
@Service
public class SAttributeServiceImpl extends ServiceImpl<SAttributeMapper, SAttribute> implements SAttributeService {

    @Autowired
    SAttributeMapper sAttributeMapper;

    /**
     * 传入商品属性名的列表如["material","people","assurance","size"]，获取相应的值
     * 传入的属性名称必须要与AttributeVO中的属性字面量对应
     * @param attributeList
     * @return
     */
    @Override
    public AttributeVO getAttribute(List<String> attributeList) {
        AttributeVO attributeVO = new AttributeVO();
        // 获取 Attribute 类的 Class 对象
        Class<?> attributeClass = attributeVO.getClass();
        ObjectMapper objectMapper = new ObjectMapper();
        LambdaQueryWrapper<SAttribute> wrapper = new LambdaQueryWrapper<>();
        attributeList.forEach(attribute->{
            wrapper.eq(SAttribute::getName, attribute).select(SAttribute::getOptions);
            try {
                List list = objectMapper.readValue(sAttributeMapper.selectOne(wrapper).getOptions(), List.class);
                // 获取属性的首字母大写形式 == Material
                String capitalizedPropertyName = attribute.substring(0, 1).toUpperCase() + attribute.substring(1);
                // 构造 setter 方法名 == setMaterial
                String setterMethodName = "set" + capitalizedPropertyName;
                // 获取 setter 方法
                java.lang.reflect.Method setterMethod = attributeClass.getMethod(setterMethodName, List.class);
                // 调用 setter 方法设置属性值 == attributeVO.setMaterial(list)
                setterMethod.invoke(attributeVO, list);
                wrapper.clear();
            } catch (JsonProcessingException | NoSuchMethodException | InvocationTargetException |
                     IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
        return attributeVO;
    }
}
